package me.numark.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import me.numark.ArticleActivity;
import me.numark.R;
import me.numark.model.News;
import me.numark.model.NewsListResponse;
import me.numark.net.GsonRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.utils.Constants;
import me.numark.utils.LogUtils;
import me.numark.utils.Settings;
import me.numark.utils.Utils;
import me.numark.view.NewsListItemViewHolder;

/**
 * Created by tian on 14-9-25:下午10:54.
 */
public class NewsListFragment extends Fragment implements OnRefreshListener2, OnItemClickListener {

    private static final String TAG = NewsListFragment.class.getSimpleName();

    private NewsAdapter mNewsAdapter;

    private int mChannelId = -1;

    private PullToRefreshListView mList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_list, container, false);
        mNewsAdapter = new NewsAdapter();
        mList = (PullToRefreshListView) view.findViewById(R.id.ptr_list);
        mList.setOnRefreshListener(this);
        mList.setAdapter(mNewsAdapter);
        mList.getRefreshableView().setOnItemClickListener(this);
        if (getArguments() != null) {
            mChannelId = getArguments().getInt("channel");
        }
        mList.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        LogUtils.d("NewsListFragment", "onStart!!!");
    }

    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        News news = mNewsAdapter.getItem(position - 1);
        Intent intent = new Intent(getActivity(), ArticleActivity.class);
        intent.putExtra(Constants.NEWS_EXTRA, news.toString());
        intent.putExtra(Constants.SHARE_COUNT, news.share_count);
        startActivity(intent);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        getNewsList(0);
//        loadCursor(getArguments());
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        getNewsList(mNewsAdapter.getCount());
    }

    private void getNewsList(final int start) {
        String url = getFeedUrl(start);
        GsonRequest<NewsListResponse> request = new GsonRequest<>(url,
                Request.Method.GET,
                NewsListResponse.class, true, null, new Response.Listener<NewsListResponse>() {
            @Override
            public void onResponse(NewsListResponse response) {
                if (response.ret) {
                    LogUtils.d("loadFeeds, feeds size is " + response.data.length);
                    if (start == 0) {
                        newsList.clear();
                    }
                    if (response.data != null) {
                        newsList.addAll(Arrays.asList(response.data));
                    }
                    mNewsAdapter.notifyDataSetChanged();
                }
                finishLoading();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                finishLoading();
                Utils.showToast(R.string.generic_network_error);
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }

    private String getFeedUrl(int start) {
        return String.format(NetworkConstants.NEWS_CHANNEL_URL,
                Settings.getUid()) + "?" + "start=" + start + "&limit="
                + Constants.PAGE_SIZE;
    }

    private class NewsAdapter extends BaseAdapter {

        Date today, yesterday, year;

        public NewsAdapter() {
            super();
            Date[] dates = Utils.getMarkDate();
            today = dates[0];
            yesterday = dates[1];
            year = dates[2];
        }


        @Override
        public int getCount() {
            return newsList.size();
        }

        @Override
        public News getItem(int position) {
            return newsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return getItem(position).id;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            NewsListItemViewHolder viewHolder;
            if (view == null) {
                view = getActivity().getLayoutInflater()
                        .inflate(R.layout.news_list_item2, parent, false);
                viewHolder = new NewsListItemViewHolder(NewsListFragment.this, view);
                view.setTag(viewHolder);
            }
            viewHolder = (NewsListItemViewHolder) view.getTag();
            LogUtils.d("getView at position " + position + ", news is " + newsList.get(position));
            viewHolder.bindData(newsList.get(position));
            return view;
        }

    }

    private void finishLoading() {
        mList.postDelayed(new Runnable() {
            @Override
            public void run() {
                mList.onRefreshComplete();
            }
        }, 100);
    }

    private List<News> newsList = new ArrayList<>();
}
